import { createSlice } from "@reduxjs/toolkit";
import axios from "axios";

const foodsStore = createSlice({
    name: 'foods',
    initialState: {
        // 商品列表
        foodsList: [],
        // 菜单激活下标值
        activeIndex: 0,
        // 购物车列表
        cartList: []
    },
    reducers: {
        // 更改商品列表
        setFoodsList(state, action) {
            state.foodsList = action.payload
        },
        // 更改菜单下标
        setActiveIndex(state, action) {
            state.activeIndex = action.payload
        },
        // 添加购物车
        addCart(state, action) {
            // 是否添加过？以action.payload.id 去cartList中匹配，匹配到了 添加过
            const item = state.cartList.find(item => item.id === action.payload.id)
            if (item) {
                item.count++
            } else {
                action.payload.count = 1
                state.cartList.push(action.payload)
            }
        },
        // 减购物车
        subCart(state, action) {
            // 是否添加过？以action.payload.id 去cartList中匹配，匹配到了 添加过
            const item = state.cartList.find(item => item.id === action.payload.id)
            item.count--
            if (item.count <= 0) {
                // 删除
                state.cartList = state.cartList.filter(item => item.id !== action.payload.id)
            }
        },
        // 清空购物车
        clearCart(state) {
            state.cartList = []
        }
    }
})
const { setFoodsList, setActiveIndex, addCart, subCart, clearCart } = foodsStore.actions
const fetchFoodsList = () => {
    return async (dispatch) => {
        const res = await axios.get('http://localhost:3004/takeaway')
        dispatch(setFoodsList(res.data))
    }
}
export { fetchFoodsList, setActiveIndex, addCart, subCart, clearCart }
const reducer = foodsStore.reducer
export default reducer